package com.oschina.sequence.test;

import com.oschina.sequence.DbPoolManger;
import com.oschina.sequence.SequenceManager;

import java.sql.Connection;
import java.sql.Statement;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by limu on 15/10/15.
 */
public class SequenceGroupTestThread implements Runnable {

    private SequenceManager sequenceManager;
    private AtomicLong success;
    private AtomicLong fail;

    public SequenceGroupTestThread(SequenceManager sequenceManager, AtomicLong success, AtomicLong fail) throws Exception {
        this.sequenceManager = sequenceManager;
        this.success = success;
        this.fail = fail;
    }

    @Override
    public void run() {
        int max = 400000;

        while (success.get() + fail.get() < max) {

            long value = 0;

            try {
                value = sequenceManager.nextValue();
                success.incrementAndGet();
            } catch (Exception e) {
                fail.incrementAndGet();
                e.printStackTrace(System.out);
            }

            try {
                if (value != 0) {
//                    insertValue(value);
                }
            } catch (Exception e) {
                fail.incrementAndGet();
                e.printStackTrace(System.out);
            }

//            System.out.println("success＝" + success.get());
//            System.out.println("fail＝" + fail.get());
        }

        System.out.println("exit thread");
    }

    private void insertValue(long value) throws Exception {
        Connection connection = DbPoolManger.getConnection(0);
        String name = sequenceManager.getAppName() + "_" + sequenceManager.getIdName();

        String sql = "insert into sequence_test(name,value) values('" + name + "', '" + value + "');";
        Statement statement = connection.createStatement();
        statement.executeUpdate(sql);

        connection.close();
    }


}
